export const createStore = (reducer, enhancer) => {
  if(enhancer){
   return enhancer(createStore)(reducer)
  }
  let listeners = [],
   currentState = {}
  function getState(){
    return currentState
  }
  function subscribe(listener){
    listeners.push(listener)
  }
  function dispatch(action){
    currentState = reducer(currentState, action)
    listeners.forEach(v => v())
  }
  //一定要进行一次初始化
  dispatch({
    type:`@#$%^&&*()`
  })
  return {
    getState,
    dispatch,
    subscribe
  }
}
//applayMiddleWare 实际上为三层嵌套函数
//第一层是在外部store中调用的传入一个middleWare进来
//第二层和第三层是在enhancer(createStore)(reducer)是调用的
//一共传入三个不同的参数(
//function 嵌套可以处理多个()
//比如一个()就是一层，对应一组参数，直接可以return，如果两个()(),对应连个组参数
//总结，想有几组参数就可以返回几层函数
export function applyMiddleware(middleware){
  return createStore => (...args) => {
      const store = createStore(...args)
      let dispatch = store.dispatch
      const midApi = {
        getState: store.getState,
        dispatch: (...args) => dispatch(...args)
      }
      dispatch = middleware(midApi)(store.dispatch)
      return {//return 的是一个处理过的store，这个store中的dispatch已经被增强
         ...store,
         dispatch
      }
    }
}

function bindDispatch(creator, dispatch){
  return (...args) => {
    dispatch(creator(...args))
  }
}

export const bindActionCreators = (creators, dispatch) => {
/*   Object.keys(creators).forEach(v => {
    bound[v] = bindDispatch(creators[v],dispatch)
  }) */
  return Object.keys(creators).reduce((total, item) => {
    total[item] = bindDispatch(creators[item], dispatch)
    return total
  }, {})

}